package cn.zch.soft.util.qrcode.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;
public class WeChatShortURL {
  public static void main(String[] args) {
    String accessToken = "";
    try {
      accessToken = getAccess_token("wx01fe6957ffde32ab", "2221b7ef7384fadcc4709e59bdc54626");
    }
    catch (ClientProtocolException e) {
      e.printStackTrace();
    }
    if (accessToken != "") {
      String longurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx01fe6957ffde32ab&redirect_uri=http%3A%2F%2Fsmartschool.singbon.com%2FnoCardPay%2Findex.do%3FselectDeviceSN%3D99391089c29680c899391089c29680c899391089c29680c879c71988859afeb491f2e222f1af8a27&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
      String shortURL = Long2Short(longurl, accessToken);
      System.out.println("shortURL  " + shortURL);
    }
  }
  // 微信获取accesstoken
  public static String getAccess_token(String AppID, String AppSecret) throws ClientProtocolException {
    String ACCESS_TOKEN = "";
    //AppSecret = "2221b7ef7384fadcc4709e59bdc54626";// 智慧净水
    //AppID = "wx01fe6957ffde32ab";// 净水
    String result = "";
    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppID + "&secret=" + AppSecret;
    HttpGet get = new HttpGet(url);
    HttpResponse response;
    try {
      response = HttpClients.createDefault().execute(get);
      if (response.getStatusLine().getStatusCode() == 200) {
        result = EntityUtils.toString(response.getEntity());
        JSONObject json = JSONObject.fromObject(result);
        ACCESS_TOKEN = json.getString("access_token");
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    TerminalManager.appIdToAccessToken.put(AppID, ACCESS_TOKEN);
    return ACCESS_TOKEN;
  }
  // 微信获取 短网址
  public static String Long2Short(String longurl, String token) {
    String sUrl = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";
    String shortURL = "";
    try {
      sUrl = sUrl.replace("ACCESS_TOKEN", token);
      String param = "{\"action\":\"long2short\"," + "\"long_url\":\"" + longurl + "\"}";
      JSONObject jsonObject = httpRequest(sUrl, "POST", param);
      System.err.println("jsonObject:" + jsonObject);
      boolean containsValue = jsonObject.toString().contains("errcode");
      if (containsValue && jsonObject.getString("errcode") != "0" && !jsonObject.getString("errcode").equals("0")) {
        String errcode = jsonObject.getString("errcode");
        System.err.println("errcode" + errcode);
      }
      else {
        shortURL = jsonObject.getString("short_url");
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return shortURL;
  }
  public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    StringBuffer buffer = new StringBuffer();
    try {
      // 创建SSLContext对象，并使用我们指定的信任管理器初始化
      TrustManager[] tm = {new MyX509TrustManager()};
      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      sslContext.init(null, tm, new java.security.SecureRandom());
      // 从上述SSLContext对象中得到SSLSocketFactory对象
      SSLSocketFactory ssf = sslContext.getSocketFactory();
      URL url = new URL(requestUrl);
      HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
      httpUrlConn.setSSLSocketFactory(ssf);
      httpUrlConn.setDoOutput(true);
      httpUrlConn.setDoInput(true);
      httpUrlConn.setUseCaches(false);
      // 设置请求方式（GET/POST）
      httpUrlConn.setRequestMethod(requestMethod);
      if ("GET".equalsIgnoreCase(requestMethod))
        httpUrlConn.connect();
      // 当有数据需要提交时
      if (null != outputStr) {
        OutputStream outputStream = httpUrlConn.getOutputStream();
        // 注意编码格式，防止中文乱码
        outputStream.write(outputStr.getBytes(StandardCharsets.UTF_8));
        outputStream.close();
      }
      // 将返回的输入流转换成字符串
      InputStream inputStream = httpUrlConn.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String str = null;
      while ((str = bufferedReader.readLine()) != null) {
        buffer.append(str);
      }
      bufferedReader.close();
      inputStreamReader.close();
      // 释放资源
      inputStream.close();
      inputStream = null;
      httpUrlConn.disconnect();
      jsonObject = JSONObject.fromObject(buffer.toString());
      System.out.println("jsonObject=" + jsonObject);
    }
    catch (ConnectException ce) {
      ce.printStackTrace();
      System.out.println("网络链接失败！");
    }
    catch (UnknownHostException uhe) {
      uhe.printStackTrace();
      System.out.println("微信API无法访问....！");
      // httpRequest(requestUrl, requestMethod, outputStr);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return jsonObject;
  }
}
